<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图区 -->
        <el-card>
            <!-- 警告框 -->
            <el-alert title="注意：只允许为第三级分类设置相关参数!" type="warning" show-icon :closable="false"></el-alert>
            <!-- 选择商品分类区 -->
            <el-row class="cat_opt">
                <el-col>
                    <span>选择商品分类：</span>
                    <!-- 级联选择框 -->
                    <el-cascader
                        v-model="selectedCateKeys"
                        :options="cateList"
                        :props="cateProps"
                        @change="handleChange()">
                    </el-cascader>
                </el-col>
            </el-row>
            <!-- tab页签区 -->
            <el-tabs v-model="activeName" @tab-click="handleTabClick()">
                <!-- 添加动态参数的面板 -->
                <el-tab-pane label="动态参数" name="many">
                    <el-button type="primary" size="mini" :disabled='isBtnDisabled' @click="addDialogVisible=true">添加参数</el-button>
                    <!-- 动态参数表格 -->
                    <el-table :data="manyTabelData" border stripe>
                        <el-table-column type="expand">
                            <template v-slot='slotProp'>
                                <!-- 循环渲染tag标签 -->
                                <el-tag v-for="(i,index) in slotProp.row.attr_vals" :key="index" closable >
                                    {{i}}
                                </el-tag>
                                <!-- 新增标签 -->
                                <el-input
                                    class="input-new-tag"
                                    v-if="slotProp.row.inputVisible"
                                    v-model="slotProp.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(slotProp.row)"
                                    @blur="handleInputConfirm(slotProp.row)">
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="islotProp.row.inputVisible=true">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index" label="#"></el-table-column> <!--索引列-->
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template v-slot='slotProp'>
                                <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(slotProp.row.attr_id)">编辑</el-button>
                                <el-button type="danger" icon="el-icon-delete" @click="removeParams(slotProp.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <!-- 添加静态参数的面板 -->
                <el-tab-pane label="静态参数" name="only">
                    <el-button type="primary" size="mini" :disabled='isBtnDisabled' @click="addDialogVisible=true">添加参数</el-button>
                    <!-- 静态参数表格 -->
                    <el-table :data="onlyTabelData" border stripe>
                        <el-table-column type="expand">
                            <template v-slot='slotProp'>
                                <!-- 循环渲染tag标签 -->
                                <el-tag v-for="(i,index) in slotProp.row.attr_vals" :key="index" closable >
                                    {{i}}
                                </el-tag>
                                <!-- 新增标签 -->
                                <el-input
                                    class="input-new-tag"
                                    v-if="slotProp.row.inputVisible"
                                    v-model="slotProp.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(slotProp.row)"
                                    @blur="handleInputConfirm(slotProp.row)">
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="islotProp.row.inputVisible=true">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index" label="#"></el-table-column> <!--索引列-->
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template v-slot='slotProp'>
                                <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(slotProp.row.attr_id)">编辑</el-button>
                                <el-button type="danger" icon="el-icon-delete" @click="removeParams(slotProp.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>
        <!-- 添加参数的对话框 -->
        <el-dialog
            :title="'添加' + titleText"
            :visible.sync="addDialogVisible"
            width="50%"
            @close='addDialogClosed()'>
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addParams()">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改参数的对话框 -->
        <el-dialog
            :title="'修改' + titleText"
            :visible.sync="editDialogVisible"
            width="50%"
            @close='editDialogClosed()'>
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editParams()">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {    
    name:'Params',
    data() {
        return {
            // 商品分类列表
            cateList:[],
            // 级联选择框数据源配置
            cateProps:{ 
                expandTrigger: 'hover',
                value:'cat_id',
                label:'cat_name',
                children:'children'
            },
            // 级联选择框双向绑定
            selectedCateKeys:[],
            // 被激活的页签
            activeName:'many',
            // 动态参数的表格
            manyTableDate:[],
            // 静态参数的表格
            onlyTableDate:[],
            // 添加参数的对话框显示/隐藏
            addDialogVisible:false,
            // 添加参数的表单数据
            addForm:{
                attr_name:''
            },
            addFormRules:{
                attr_name:[{required:true,message:'请输入参数',trigger:'blur'}]
            },

            editDialogVisible:false,
            editForm:{
                attr_name:''
            },
            editFormRules:{
                attr_name:[{required:true,message:'请输入参数',trigger:'blur'}]
            }
        }
    },
    methods: {
        // 获取所有的商品分类列表
        async getCateList(){
            const {data:result}=await this.$http.get('categories',{params:{type:3}})
            if(result.meta.status!==200){
                this.$message.error('获取商品分类数据失败')
            }else{
                this.cateList=result.data
                console.log(this.cateList)
            }
        },
        // 级联选择框选中项变化触发的回调
        async handleChange(){
            this.getParamsData()
        },
        // Tab页签点击事件的回调
        handleTabClick(){
            this.getParamsData()
        },
        // 获取动态/静态参数列表
        async getParamsData(){
            if(this.selectedCateKeys.length!==3){
                this.selectedCateKeys=[]
                this.manyTableDate=[]
                this.onlyTableDate=[]
                this.$message.error('必须选择三级分类')
            }else{
                // 根据所选分类的ID和当前的面板获取对应的参数
                const {data:result}=await this.$http.get(`categories/${this.cateId}/attributes`,{params:{sel:this.activeName}})
                if(result.meta.status!==200){
                    this.$message.error('获取参数列表失败')
                }else{
                    result.data.forEach((item)=>{
                        item.attr_vals=item.attr_vals ? item.attr_vals.split(' ') : []
                        // 控制新增tag的显示与隐藏
                        item.inputVisible=false
                        item.inputValue=''
                    })
                    // 判断是静态还是动态参数
                    if(this.activeName==='many'){
                        this.manyTableDate=result.data
                    }else{
                        this.onlyTableDate=result.data
                    }
                }
            }
        },
        addDialogClosed(){
            this.$refs['addFormRef'].resetFields()
        },
        // 添加参数的确定按钮的回调
        addParams(){
            this.$refs['addFormRef'].validate(async (valid)=>{
                if(!valid){
                    return
                }else{
                    const {data:result}=await this.$http.post(`categories/${this.cateId}/attributes`,{attr_name:this.addForm.attr_name, attr_sel:this.activeName})
                    if(result.meta.status!==201){
                        this.$message.error('添加参数失败')
                    }else{
                        this.addDialogVisible=false
                        this.getParamsData()
                        this.$message.success('添加参数成功')
                    }
                }
            })
        },
        // 点击编辑按钮，修改商品参数
        async showEditDialog(id){
            const {data:result}=await this.$http.get(`categories/${this.cateId}/attributes/${id}`,{params:{attr_sel:this.activeName}})
            if(result.meta.status!==200){
                this.$message.error('获取参数信息失败')
            }else{
                this.editForm=result.data
                this.editDialogVisible=true
            }
        },
        editDialogClosed(){
            this.$refs['editFormRef'].resetFields()
        },
        editParams(){
            this.$refs['editFormRef'].validate(async (valid)=>{
                if(!valid){return}else{
                    const {data:result}=await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,{attr_name:this.editForm.attr_name, attr_sel:this.activeName})
                    if(result.meta.status!==200){
                        this.$message.error('修改参数失败')
                    }else{
                        this.$message.success('修改参数成功')
                        this.getParamsData()
                        this.editDialogVisible=false
                    }
                }
            })
        },
        // 删除
        async removeParams(id){
            const confirmResult=await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err=>err)
            if(confirmResult!=='confirm'){
                this.$message.info('已取消')
            }else{
                const {data:result}=await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
                if(result.meta.status!==200){
                    this.$message.error('删除失败')
                }else{
                    this.getParamsData()
                    this.$message.success('删除成功')
                }
            }
        },
        async handleInputConfirm(row){
            if(row.inputValue.trim().length===0){
                row.inputValue=''
                row.inputVisible=false
            }else{
                row.attr_vals.push(row.inputValue.trim())
                const {data:result}=await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{attr_name:row.attr_name,attr_sel:row.attr_sel,attr_vals:row.inputValue.join(' ')})
                if(result.meta.status!==200){
                    this.$message.error('失败了')
                }else{
                    row.inputValue=''
                    row.inputVisible=false
                }
            }
        }
    },
    computed:{
        // 如果级联选择器选择的商品是三级分类，那么按钮才能用，否则禁用
        isBtnDisabled(){
            if(this.selectedCateKeys.length!==3){
                return true
            }else{
                return false
            }
        },
        // 当前选中的三级分类的ID
        cateId(){
            if(this.selectedCateKeys.length===3){
                return this.selectedCateKeys[2] 
            }else{
                return null
            }
        },
        // 对话框标题的文本
        titleText(){
            if(this.activeName='many'){
                return '动态参数'
            }else{
                return '静态参数'
            }
        }
    },
    created(){
        this.getCateList()
    }
}
</script>

<style lang='less' scoped>
.cat_opt{
    margin: 15px 0;
}

.el-cascader-panel{
    height: 200px;
}

.input-new-tag{
    width: 150px;
}
</style>